package com.kaizeli.website.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kaizeli.website.mapper.ProjectAcceptanceMapper;
import com.kaizeli.website.pojo.entity.ProjectAcceptance;
import com.kaizeli.website.pojo.dto.ProjectAcceptanceDTO;
import com.kaizeli.website.service.ProjectAcceptanceService;
import com.kaizeli.website.service.ProjectBasicInfoService;
import com.kaizeli.website.pojo.entity.ProjectBasicInfoDO;
import com.kaizeli.website.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 项目验收单服务实现类
 */
@Service
public class ProjectAcceptanceServiceImpl extends ServiceImpl<ProjectAcceptanceMapper, ProjectAcceptance> implements ProjectAcceptanceService {

    @Autowired
    private ProjectAcceptanceMapper projectAcceptanceMapper;

    // 注入开票服务，在验收完成后自动创建开票单
    @Autowired(required = false)
    private com.kaizeli.website.service.InvoiceService invoiceService;
    
    // 注入项目基础信息服务，用于更新项目状态
    @Autowired
    private ProjectBasicInfoService projectBasicInfoService;

    @Override
    public Result<List<ProjectAcceptanceDTO>> getAcceptanceByProjectId(Long projectId) {
        try {
            List<ProjectAcceptanceDTO> acceptances = projectAcceptanceMapper.selectByProjectId(projectId);
            return Result.success(acceptances);
        } catch (Exception e) {
            return Result.error(500, "查询验收单失败：" + e.getMessage());
        }
    }

    @Override
    public Result<ProjectAcceptanceDTO> getAcceptanceById(Long id) {
        try {
            ProjectAcceptanceDTO acceptance = projectAcceptanceMapper.selectByIdWithMembers(id);
            if (acceptance == null) {
                return Result.error(404, "验收单不存在");
            }
            return Result.success(acceptance);
        } catch (Exception e) {
            return Result.error(500, "查询验收单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<ProjectAcceptance> createAcceptance(ProjectAcceptance acceptance) {
        try {
            // 数据校验
            if (acceptance.getAcceptanceNo() == null || acceptance.getAcceptanceNo().trim().isEmpty()) {
                return Result.error(400, "验收单编号不能为空");
            }
            if (acceptance.getProjectId() == null) {
                return Result.error(400, "项目ID不能为空");
            }
            
            // createTime 和 updateTime 由 AutoFillPlugin 自动填充，不需要手动设置
            acceptance.setStatus("待验收");
            save(acceptance);
            return Result.success(acceptance);
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细错误信息
            return Result.error(500, "创建验收单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> updateAcceptance(Long id, ProjectAcceptance acceptance) {
        try {
            ProjectAcceptance existingAcceptance = getById(id.intValue());
            if (existingAcceptance == null) {
                return Result.error(404, "验收单不存在");
            }
            
            Long projectId = existingAcceptance.getProjectId();
            boolean statusChangedToAccepted = !"已验收".equals(existingAcceptance.getStatus()) && 
                                            "已验收".equals(acceptance.getStatus());
            
            acceptance.setId(id.intValue());
            acceptance.setUpdateTime(LocalDateTime.now());
            updateById(acceptance);
            
            // 如果验收单状态更新为"已验收"，检查项目所有验收单是否都已验收
            if (statusChangedToAccepted && projectId != null) {
                checkAndUpdateProjectStatus(projectId);
            }
            
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "更新验收单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> updateAcceptanceStatus(Long id, String status) {
        try {
            int result = projectAcceptanceMapper.updateStatus(id, status);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error(404, "验收单不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "更新验收单状态失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> deleteAcceptance(Long id) {
        try {
            boolean result = removeById(id.intValue());
            if (result) {
                return Result.success();
            } else {
                return Result.error(404, "验收单不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "删除验收单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> submitAcceptance(Long id) {
        try {
            ProjectAcceptance acceptance = getById(id.intValue());
            if (acceptance == null) {
                return Result.error(404, "验收单不存在");
            }
            
            if (!"待验收".equals(acceptance.getStatus())) {
                return Result.error(400, "只有待验收状态的验收单才能提交");
            }
            
            acceptance.setStatus("验收中");
            acceptance.setUpdateTime(LocalDateTime.now());
            updateById(acceptance);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "提交验收单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> reviewAcceptance(Long id, String status, String remark) {
        try {
            ProjectAcceptance acceptance = getById(id.intValue());
            if (acceptance == null) {
                return Result.error(404, "验收单不存在");
            }
            
            if (!"验收中".equals(acceptance.getStatus())) {
                return Result.error(400, "只有验收中状态的验收单才能审核");
            }
            
            acceptance.setStatus(status);
            if (remark != null) {
                acceptance.setRemark(remark);
            }
            acceptance.setUpdateTime(LocalDateTime.now());
            updateById(acceptance);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "审核验收单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> completeAcceptance(Long id) {
        try {
            ProjectAcceptance acceptance = getById(id.intValue());
            if (acceptance == null) {
                return Result.error(404, "验收单不存在");
            }
            
            acceptance.setStatus("已验收");
            acceptance.setAcceptanceCompletionTime(LocalDateTime.now());
            acceptance.setUpdateTime(LocalDateTime.now());
            updateById(acceptance);
            
            // 自动为验收单创建开票单
            if (invoiceService != null) {
                try {
                    invoiceService.createInvoiceFromAcceptance(id.intValue());
                } catch (Exception e) {
                    // 记录日志但不影响验收完成
                    System.err.println("自动创建开票单失败: " + e.getMessage());
                }
            }
            
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "完成验收单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> updateAcceptanceCompletionTime(Long id, String completionTime) {
        try {
            ProjectAcceptance acceptance = getById(id.intValue());
            if (acceptance == null) {
                return Result.error(404, "验收单不存在");
            }
            
            LocalDateTime completionDateTime = LocalDateTime.parse(completionTime);
            acceptance.setAcceptanceCompletionTime(completionDateTime);
            acceptance.setUpdateTime(LocalDateTime.now());
            updateById(acceptance);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "更新验收完成时间失败：" + e.getMessage());
        }
    }

    @Override
    public List<ProjectAcceptanceDTO> getAcceptancesByProjectCode(String projectCode) {
        try {
            return projectAcceptanceMapper.selectByProjectCode(projectCode);
        } catch (Exception e) {
            throw new RuntimeException("根据项目编号查询验收单失败：" + e.getMessage());
        }
    }

    @Override
    public List<ProjectAcceptanceDTO> getAcceptancesByProjectId(Long projectId) {
        try {
            return projectAcceptanceMapper.selectByProjectId(projectId);
        } catch (Exception e) {
            throw new RuntimeException("根据项目ID查询验收单失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查项目所有验收单是否都已验收，如果是则更新项目状态为"已验收"
     */
    private void checkAndUpdateProjectStatus(Long projectId) {
        try {
            // 查询该项目下所有验收单
            List<ProjectAcceptanceDTO> acceptances = projectAcceptanceMapper.selectByProjectId(projectId);
            
            // 如果没有验收单，直接返回
            if (acceptances == null || acceptances.isEmpty()) {
                return;
            }
            
            // 检查是否所有验收单都已验收
            boolean unlikeAcceptancesExist = acceptances.stream()
                    .anyMatch(acc -> !"已验收".equals(acc.getStatus()) && 
                                   !"已作废".equals(acc.getStatus()) && 
                                   !"作废审批中".equals(acc.getStatus()));
            
            // 如果所有验收单都已验收，更新项目状态
            if (!unlikeAcceptancesExist) {
                ProjectBasicInfoDO project = new ProjectBasicInfoDO();
                project.setId(projectId);
                project.setStatus("已验收");
                projectBasicInfoService.update(project);
                System.out.println("项目 " + projectId + " 所有验收单已验收，项目状态已更新为'已验收'");
            }
        } catch (Exception e) {
            // 记录日志但不影响验收单更新
            System.err.println("检查并更新项目状态失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}